package controller_book

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"tools-api/src/common/utils"
	"tools-api/src/jcj/model"
	"tools-api/src/jcj/service/service_book"
	"tools-api/src/routes/request"
	"tools-api/src/routes/response"
)

// TypesGetList 获取类别列表
func TypesGetList(ctx *gin.Context) {
	_type := utils.Str2Int(ctx.Query("type"))
	isSet := utils.Str2Bool(ctx.Query("is_set")) // 是否是设置加载列表
	if _type != 1 && _type != 2 {
		response.Fail(ctx, "参数错误")
		return
	}
	list := service_book.TypesGetList(request.GetCurrentUser(ctx), _type, isSet)
	response.Success(ctx, list)
}

// TypesAdd 添加类别
func TypesAdd(ctx *gin.Context) {
	var req = struct {
		Key  string `json:"key"`
		Name string `json:"name"`
		Type int    `json:"type"`
	}{}
	_ = ctx.ShouldBindBodyWith(&req, binding.JSON)
	if req.Key == "" || req.Name == "" {
		response.Fail(ctx, "参数错误")
		return
	}
	types := model.BookTypes{
		Uuid: request.GetCurrentUser(ctx),
		Key:  req.Key,
		Name: req.Name,
		Type: req.Type,
	}
	id := service_book.TypesAdd(types)
	if id == 0 {
		response.Fail(ctx, "添加失败")
		return
	}
	response.SuccessMsg(ctx, "添加成功")
}

// TypesSort 排序
func TypesSort(ctx *gin.Context) {
	var req = struct {
		Arr string `json:"arr"`
	}{}
	if err := ctx.ShouldBindBodyWith(&req, binding.JSON); err != nil {
		response.Fail(ctx, "参数错误")
		return
	}
	var arr [][]int64
	_ = json.Unmarshal([]byte(req.Arr), &arr)
	if len(arr) > 0 {
		_ = service_book.TypesSort(request.GetCurrentUser(ctx), arr)
	}
	response.SuccessMsg(ctx, "")
}

// TypesDelete 单个删除类别
func TypesDelete(ctx *gin.Context) {
	id := utils.Str2Int64(ctx.Param("id"))
	if id <= 0 {
		response.Fail(ctx, "参数错误")
		return
	}
	transferTo := utils.Str2Int64(ctx.Query("transfer_to"))
	var err error
	if transferTo > 0 { // 转移后删除
		if id == transferTo {
			response.Fail(ctx, "请选择不同账户进行转移")
			return
		}
		err = service_book.TypesTransformDelete(request.GetCurrentUser(ctx), id, transferTo)
	} else { // 直接删除
		err = service_book.TypesDelete(request.GetCurrentUser(ctx), id)
	}
	if err != nil {
		response.Fail(ctx, "删除失败")
		return
	}
	response.SuccessMsg(ctx, "删除成功")
}
